{% extends 'base.html' %}

{% block title %}
产品列表 - 数据管理系统
{% endblock %}

{% block breadcrumb %}
<li class="breadcrumb-item active" aria-current="page">产品列表</li>
{% endblock %}

{% block content %}
<!-- 路由快捷导航按钮 -->
<div class="d-flex justify-content-start flex-wrap gap-2 mb-4">
  <a href="{{ url_for('list_companies') }}" class="btn btn-outline-secondary btn-sm">📋 查看公司</a>
  <a href="{{ url_for('list_salespersons') }}" class="btn btn-outline-info btn-sm">📋 查看销售员</a>
  <a href="{{ url_for('list_currencies') }}" class="btn btn-outline-info btn-sm">📋 查看货币</a>
  <a href="{{ url_for('cart.list_quotations') }}" class="btn btn-outline-info btn-sm">📋 查看所有报价单</a>
  {% if current_user.has_permission('admin') %}
  <a href="{{ url_for('admin_manage') }}" class="btn btn-outline-info btn-sm">📋 管理权限</a>
  {% endif %}
</div>

<!-- 图片模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-xl">
    <div class="modal-content bg-transparent border-0">
      <div class="modal-body p-0 text-center">
        <img id="modalImage" src="" alt="放大图片" class="img-fluid" style="max-height: 80vh;" />
      </div>
    </div>
  </div>
</div>

<div class="d-flex justify-content-between align-items-center mb-4">
  <h2 class="page-header">产品列表</h2>
  <div>
    <button id="addToCartBtn" class="btn btn-primary me-2" disabled><i class="bi bi-cart-plus"></i> 添加到购物车</button>
    <a href="{{ url_for('cart.cart') }}" class="btn btn-primary"><i class="bi bi-cart"></i> 查看购物车</a>

    <a href="{{ url_for('add_main') }}" class="btn btn-primary ms-2"><i class="bi bi-plus-lg"></i> 添加产品</a>
  </div>
</div>
<div id="cartStatus" class="text-muted small mt-2"></div>
<!-- 新增：居中提示框 -->
<div id="notification" class="position-fixed top-50 start-50 translate-middle px-4 py-3 rounded shadow-lg z-50"
  style="display: none; background-color: rgba(220,53,69,0.9);">
 
  <p id="notificationMessage" class="text-white mb-0"></p>
</div>

<div class="table-responsive">
  <table class="table table-striped table-hover">
    <thead class="table-light">
      <tr>
        <th scope="col">
          <input type="checkbox" id="selectAll" class="form-check-input larger-checkbox" title="全选" />
        </th>
        <th scope="col">ID</th>
        {% if current_user.has_permission('admin') %}
        <th scope="col">用户</th>
        {% endif %}
        <th scope="col">图片</th>
        <th scope="col">标题</th>
        <th scope="col">规格</th>
        <th scope="col">价格范围</th>
        <th scope="col">MOQ</th>
        <th scope="col">公司名称</th>
        <th scope="col">操作</th>
      </tr>
    </thead>
    <tbody>
      {% for main in mains %}
      <tr class="clickable-row" data-product-id="{{ main.id }}">
        <td>
          <input type="checkbox" class="product-checkbox form-check-input larger-checkbox"
            data-product-id="{{ main.id }}" title="选择产品" />
        </td>
        <td scope="row">{{ main.id }}</td>
        {% if current_user.has_permission('admin') %}
        <td>{{ main.user.username or '未知用户' }}</td>
        {% endif %}
        <td class="col-2"> <!-- 调整为合适的列宽比例 -->
          {% if main.details and main.details.0.image_url %}
          <a href="javascript:void(0);"
            onclick="showImageModal('{{ url_for('static', filename=main.details.0.display_image_url) }}')">
            <img src="{{ url_for('static', filename=main.details.0.display_image_url) }}" alt="产品图片"
              class="img-thumbnail" style="width: 150px; height: 150px; object-fit: contain;" />
          </a>
          {% else %}
          <span class="text-muted">无图片</span>
          {% endif %}
        </td>
        <td class="col-3 align-middle text-break"> <!-- 使用 text-break 强制换行 -->
          <a href="{{ main.url }}" target="_blank" class="text-decoration-none">
            {{ main.title }}
          </a>
        </td>
        <td class="col-2 align-middle text-break">
          <!-- <a href="{{ main.url }}" target="_blank" class="text-decoration-none"> -->
          {{ main.details.0.self_model }}
          <!-- </a> -->
        </td>
        <td>
          {% if main.min_price == main.max_price %}
          <span class="badge bg-success">¥{{ '%.2f'|format(main.min_price) }}</span>
          {% else %}
          <div>
            <span class="badge bg-primary">¥{{ '%.2f'|format(main.min_price) }}</span>
            至
            <span class="badge bg-primary">¥{{ '%.2f'|format(main.max_price) }}</span>
          </div>
          {% endif %}
          <small class="text-muted d-block mt-1">{{ main.spec_count }}种规格</small>
        </td>
        <td>
          <span class="badge bg-secondary">{{ main.min_moq }}</span>
        </td>
        <td class="col-2 align-middle text-break">
          <a href="{{ main.company_url }}" target="_blank" class="text-decoration-none">
            {{ main.company_name }}
          </a>
        </td>
        <td class="action-buttons">
          <div class="d-flex flex-nowrap gap-2">
            <a href="{{ url_for('list_details', product_id=main.id) }}" class="btn btn-sm btn-outline-success"
              target="_blank">详情</a>
            <a href="{{ url_for('edit_main', id=main.id) }}" class="btn btn-sm btn-outline-primary">编辑</a>
            <div class="ms-1">
              <button type="button" class="btn btn-sm btn-outline-danger"
                onclick="if(confirm('确定删除吗?')) window.location='{{ url_for('delete_main', id=main.id) }}'">
                <i class="bi bi-trash"></i>
                <span class="d-none d-sm-inline">删除</span>
              </button>
            </div>
          </div>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>

<!-- 分页导航 -->
<nav aria-label="Page navigation" class="mt-5">
  <ul class="pagination justify-content-center flex-wrap gap-1">
    <!-- 上一页按钮 -->
    <li class="page-item {% if not pagination.has_prev %}disabled{% endif %}">
      <a class="page-link rounded-md shadow-sm border-0 transition-all duration-200 hover:shadow-md hover:bg-primary/5 focus:outline-none focus:ring-2 focus:ring-primary/20"
        href="{{ url_for('list_main', page=pagination.prev_num) if pagination.has_prev else '#' }}"
        aria-label="Previous">
        <span aria-hidden="true">«</span>
      </a>
    </li>

    <!-- 数字页码 -->
    {% set left_pages = [pagination.page - 1, pagination.page - 2, pagination.page - 3] | select('>', 0) | list %}
    {% set right_pages = [pagination.page + 1, pagination.page + 2, pagination.page + 3] | select('<', pagination.pages
      + 1) | list %} <!-- 第一页 -->
      {% if pagination.page > 4 %}
      <li class="page-item">
        <a class="page-link rounded-md shadow-sm border-0 transition-all duration-200 hover:shadow-md hover:bg-primary/5 focus:outline-none focus:ring-2 focus:ring-primary/20"
          href="{{ url_for('list_main', page=1) }}">1</a>
      </li>
      {% if pagination.page > 5 %}
      <li class="page-item">
        <span class="page-link rounded-md border-0 bg-transparent text-muted">...</span>
      </li>
      {% endif %}
      {% endif %}

      <!-- 左侧页码 -->
      {% for p in left_pages | reverse %}
      <li class="page-item">
        <a class="page-link rounded-md shadow-sm border-0 transition-all duration-200 hover:shadow-md hover:bg-primary/5 focus:outline-none focus:ring-2 focus:ring-primary/20"
          href="{{ url_for('list_main', page=p) }}">{{ p }}</a>
      </li>
      {% endfor %}

      <!-- 当前页码 -->
      <li class="page-item active" aria-current="page">
        <span
          class="page-link rounded-md bg-primary text-white shadow-sm border-0 transition-all duration-200 hover:shadow-md hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary/30">
          {{ pagination.page }}
        </span>
      </li>

      <!-- 右侧页码 -->
      {% for p in right_pages %}
      <li class="page-item">
        <a class="page-link rounded-md shadow-sm border-0 transition-all duration-200 hover:shadow-md hover:bg-primary/5 focus:outline-none focus:ring-2 focus:ring-primary/20"
          href="{{ url_for('list_main', page=p) }}">{{ p }}</a>
      </li>
      {% endfor %}

      <!-- 最后一页 -->
      {% if pagination.page < pagination.pages - 3 %} {% if pagination.page < pagination.pages - 4 %} <li
        class="page-item">
        <span class="page-link rounded-md border-0 bg-transparent text-muted">...</span>
        </li>
        {% endif %}
        <li class="page-item">
          <a class="page-link rounded-md shadow-sm border-0 transition-all duration-200 hover:shadow-md hover:bg-primary/5 focus:outline-none focus:ring-2 focus:ring-primary/20"
            href="{{ url_for('list_main', page=pagination.pages) }}">{{ pagination.pages }}</a>
        </li>
        {% endif %}

        <!-- 下一页按钮 -->
        <li class="page-item {% if not pagination.has_next %}disabled{% endif %}">
          <a class="page-link rounded-md shadow-sm border-0 transition-all duration-200 hover:shadow-md hover:bg-primary/5 focus:outline-none focus:ring-2 focus:ring-primary/20"
            href="{{ url_for('list_main', page=pagination.next_num) if pagination.has_next else '#' }}"
            aria-label="Next">
            <span aria-hidden="true">»</span>
          </a>
        </li>
  </ul>

  <p class="text-center text-muted mt-2">
    显示第 {{ pagination.first_item if pagination.items else 0 }}-{{ pagination.last_item if pagination.items else 0 }} 条，共
    {{ pagination.total }} 条记录
  </p>
</nav>

<div class="export-container">
  <a href="{{ url_for('export_page') }}" class="btn btn-primary">导出所有记录</a>
</div>

<div id="collectStatus" class="text-muted small">
  <button id="collectPricesBtn" class="btn btn-warning mb-3" onclick="collect()">采集缺失价格</button>
</div>


{% endblock %}

{% block styles %}
<style>
  /* 增大复选框 */
  .larger-checkbox {
    transform: scale(1.5);
    margin: 0.5rem;
  }

  /* 为可点击行添加悬停效果 */
  .clickable-row {
    cursor: pointer;
  }

  .clickable-row:hover {
    background-color: #f8f9fa;
    /* Bootstrap 的浅灰色悬停效果 */
  }
</style>
{% endblock %}

{% block scripts %}
<script>
  // 初始化工具提示和模态框
  document.addEventListener('DOMContentLoaded', function () {
    // 初始化 Bootstrap工具提示
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    })

    // 图片模态框点击事件
    document.getElementById('imageModal').addEventListener('click', function (e) {
      if (e.target === this) {
        bootstrap.Modal.getInstance(this).hide()
      }
    })
    document.getElementById('modalImage').addEventListener('click', function (e) {
      e.stopPropagation()
    })

    // 复选框和行点击逻辑
    const selectAllCheckbox = document.getElementById('selectAll')
    const productCheckboxes = document.querySelectorAll('.product-checkbox')
    const addToCartBtn = document.getElementById('addToCartBtn')
    const cartStatus = document.getElementById('cartStatus')

    // 更新按钮状态
    function updateButtonState() {
      const selectedIds = Array.from(productCheckboxes).filter((cb) => cb.checked)
      addToCartBtn.disabled = selectedIds.length === 0
    }

    // 全选复选框事件
    selectAllCheckbox.addEventListener('change', function () {
      productCheckboxes.forEach((cb) => {
        cb.checked = this.checked
      })
      updateButtonState()
    })

    // 单选复选框事件
    productCheckboxes.forEach((cb) => {
      cb.addEventListener('change', function (e) {
        e.stopPropagation()
        selectAllCheckbox.checked = Array.from(productCheckboxes).every((cb) => cb.checked)
        updateButtonState()
      })
    })

    // 行点击事件
    document.querySelectorAll('.clickable-row').forEach((row) => {
      row.addEventListener('click', function (e) {
        if (e.target.tagName === 'A' || e.target.tagName === 'BUTTON' || e.target.closest('a') || e.target.closest('button') || e.target.tagName === 'INPUT' || e.target.closest('.action-buttons')) {
          return
        }

        const checkbox = row.querySelector('.product-checkbox')
        checkbox.checked = !checkbox.checked
        selectAllCheckbox.checked = Array.from(productCheckboxes).every((cb) => cb.checked)
        updateButtonState()
      })
    })

    // 添加到购物车按钮事件
    addToCartBtn.addEventListener('click', function () {
      this.disabled = true
      cartStatus.textContent = '正在添加...'

      const selectedIds = Array.from(productCheckboxes)
        .filter((cb) => cb.checked)
        .map((cb) => cb.dataset.productId)

      fetch('{{ url_for("cart.add_to_cart") }}', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ product_ids: selectedIds })
      })
        .then((res) => res.json())
        .then((data) => {
          cartStatus.textContent = data.message
          if (data.success) {
            productCheckboxes.forEach((cb) => (cb.checked = false))
            selectAllCheckbox.checked = false
            updateButtonState()
          }
        })
        .catch((err) => {
          console.error(err)
          cartStatus.textContent = '添加失败，请检查控制台或后端日志'
        })
        .finally(() => {
          this.disabled = false
        })
    })
  })



  // 显示图片模态框
  function showImageModal(imageUrl) {
    document.getElementById('modalImage').src = imageUrl
    var modal = new bootstrap.Modal(document.getElementById('imageModal'))
    modal.show()
  }

  // 采集价格
  function collect() {
    document.getElementById('collectPricesBtn').addEventListener('click', function () {
      this.disabled = true
      document.getElementById('collectStatus').innerText = '已开始采集，请耐心等待（每20秒采集1个链接）...'

      fetch('/collect_missing_prices', {
        method: 'POST'
      })
        .then((res) => res.json())
        .then((data) => {
          document.getElementById('collectStatus').innerText = data.message
        })
        .catch((err) => {
          console.error(err)
          document.getElementById('collectStatus').innerText = '请求失败，请检查控制台或后端日志'
        })
    })
  }
  // 删除产品函数
  function deleteProduct(id) {
    if (confirm('确定删除吗?')) {
      fetch(`/main/delete/${id}`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json'
        }
      })
        .then(response => {
          if (!response.ok) {
            return response.json().then(err => { throw err; });
          }
          return response.json();
        })
        .then(data => {
          if (data.status === 'success') {
            window.location.reload(); // 删除成功刷新页面
          } else {
            showNotification(data.message); // 显示错误消息
          }
        })
        .catch(error => {
          showNotification(error.message || '删除产品时发生错误');
        });
    }
  }

  // 显示通知函数
  function showNotification(message) {
    const notification = document.getElementById('notification');
    const notificationMessage = document.getElementById('notificationMessage');

    notificationMessage.textContent = message;
    notification.style.display = 'block';

    // 2秒后消失
    setTimeout(() => {
      notification.style.opacity = '0';
      setTimeout(() => {
        notification.style.display = 'none';
        notification.style.opacity = '1';
      }, 300);
    }, 2000);
  }

  // 修改删除按钮的onclick事件
  document.querySelectorAll('.btn-outline-danger').forEach(btn => {
    btn.onclick = function () {
      const productId = this.closest('tr').getAttribute('data-product-id');
      deleteProduct(productId);
    };
  });
</script>
{% endblock %}